import type {
  ComputeContext,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { FormRulesExt } from '#/api';

import { compute } from '@fast-crud/fast-crud';

import { RuleType } from '#/api';
import { DefUserApi } from '#/api/devOperation/tenant/defUser';
import { $t } from '#/locales';
import { YES_NO_CONSTANT_DICT } from '#/plugins/fast-crud/common';

export function createCrudOptions(): CreateCrudOptionsRet {
  return {
    crudOptions: {
      request: { addRequest: DefUserApi.resetRequest },
      form: { mode: 'add' },
      columns: {
        id: {
          title: 'ID',
          type: 'text',
          form: { show: false },
        },
        isUseSystemPassword: {
          title: '使用系统内置密码',
          type: 'dict-radio',
          dict: YES_NO_CONSTANT_DICT,
          form: {
            col: { span: 24 },
            value: true,
            component: {
              optionName: 'a-radio-button',
            },
          },
        },
        password: {
          title: $t('devOperation.tenant.defUser.password'),
          type: 'password',
          form: {
            col: { span: 24 },
            show: compute((context: ComputeContext) => {
              return !context.form.isUseSystemPassword;
            }),
            component: {
              autocomplete: 'new-password',
            },
          },
        },
        confirmPassword: {
          title: '确认密码',
          type: 'password',
          form: {
            col: { span: 24 },
            show: compute((context: ComputeContext) => {
              return !context.form.isUseSystemPassword;
            }),
            component: {
              autocomplete: 'off',
            },
          },
        },
      },
    },
  };
}

export const frontRules = (formRef: Ref): FormRulesExt => {
  return {
    password: {
      type: RuleType.and,
      rules: [{ required: true, message: '请输入密码' }],
    },
    confirmPassword: {
      type: RuleType.and,
      rules: [
        { required: true, message: '请输入确认密码' },
        {
          trigger: ['blur', 'change'],
          type: 'string',
          asyncValidator: async (_: any, value: string, callback) => {
            if (value) {
              const { getFormData } = formRef.value;
              const model = await getFormData();
              if (value !== model.password) {
                return callback('2次密码不一致');
              }
            }
            return callback();
          },
        },
      ],
    },
  };
};
